package com.fish.anne.webapp.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.mail.SimpleMailMessage;

import com.fish.anne.Constants;
import com.fish.anne.model.Member;
import com.fish.anne.model.SystemAdminUser;
import com.fish.anne.model.User;
import com.fish.anne.service.MailEngine;
import com.fish.anne.webapp.util.RequestUtil;
import com.fish.anne.webapp.util.WebContextKey;
import com.opensymphony.xwork2.ActionSupport;


/**
 * Implementation of <strong>ActionSupport</strong> that contains 
 * convenience methods for subclasses.  For example, getting the current
 * user and saving messages/errors. This class is intended to
 * be a base class for all Action classes.
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class BaseAction extends ActionSupport implements SessionAware{
    private static final long serialVersionUID = 3525445612504421307L;

    /**
     * Constant for cancel result String
     */
    public static final String CANCEL = "cancel";
    
    
    protected String forward;
    
    public String getForward() {
		return forward;
	}

	public void setForward(String forward) {
		this.forward = forward;
	}
	private Integer pageCurrentPage;
    
    public Integer getPageCurrentPage() {
    	if(pageCurrentPage==null){
    		pageCurrentPage = 1;
    	}
		return pageCurrentPage;
	}

	public void setPageCurrentPage(Integer pageCurrentPage) {
		this.pageCurrentPage = pageCurrentPage;
	}
	protected Map session;
    
    public static final String ADMIN_LOGIN = "adminLogin";
    
    public SystemAdminUser getSystemAdminUser() {
		return (SystemAdminUser) session.get(WebContextKey.ADMIN_USER);
	}
    
    public Member getLoginedMember() {
		return (Member) session.get(WebContextKey.MEMBER);
	}
    
    
    public Long getLoginedMemberId() {
    	Member mb = getLoginedMember();
    	if(mb==null){
    		return 0L;
    	}
		return mb.getMemberId();
	}
    /**
     * Transient log to prevent session synchronization issues - children can use instance for logging.
     */
    protected transient final Log log = LogFactory.getLog(getClass());
 
 

    /**
     * Indicator if the user clicked cancel
     */
    protected String cancel;

    /**
     * Indicator for the page the user came from.
     */
    protected String from;

    /**
     * Set to "delete" when a "delete" request parameter is passed in
     */
    protected String delete;

    /**
     * Set to "save" when a "save" request parameter is passed in
     */
    protected String save;

    /**
     * MailEngine for sending e-mail
     */
    protected MailEngine mailEngine;

    /**
     * A message pre-populated with default data
     */
    protected SimpleMailMessage mailMessage;

    /**
     * Velocity template to use for e-mailing
     */
    protected String templateName;

    /**
     * Simple method that returns "cancel" result
     * @return "cancel"
     */
    public String cancel() {
        return CANCEL;
    }

    /**
     * Save the message in the session, appending if messages already exist
     * @param msg the message to put in the session
     */
    @SuppressWarnings("unchecked")
    protected void saveMessage(String msg) {
    	List<String> messages = (List<String>) getRequest().getSession().getAttribute("msgs");
		if (messages == null) {
			messages = new ArrayList<String>();
		}
		messages.add(msg);
		getRequest().getSession().setAttribute("msgs", messages);
    }

    /**
     * Convenience method to get the Configuration HashMap
     * from the servlet context.
     *
     * @return the user's populated form from the session
     */
    protected Map getConfiguration() {
        Map config = (HashMap) getSession().getServletContext().getAttribute(Constants.CONFIG);
        // so unit tests don't puke when nothing's been set
        if (config == null) {
            return new HashMap();
        }
        return config;
    }

    /**
     * Convenience method to get the request
     * @return current request
     */
    protected HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    /**
     * Convenience method to get the response
     * @return current response
     */
    protected HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * Convenience method to get the session. This will create a session if one doesn't exist.
     * @return the session from the request (request.getSession()).
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * Convenience method to send e-mail to users
     * @param user the user to send to
     * @param msg the message to send
     * @param url the URL to the application (or where ever you'd like to send them)
     */
    protected void sendUserMessage(User user, String msg, String url) {
        if (log.isDebugEnabled()) {
            log.debug("sending e-mail to user [" + user.getEmail() + "]...");
        }

        mailMessage.setTo(user.getFullName() + "<" + user.getEmail() + ">");

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("user", user);
        // TODO: figure out how to get bundle specified in struts.xml
        // model.put("bundle", getTexts());
        model.put("message", msg);
        model.put("applicationURL", url);
        mailEngine.sendMessage(mailMessage, templateName, model);
    }

 

    public void setMailEngine(MailEngine mailEngine) {
        this.mailEngine = mailEngine;
    }

    public void setMailMessage(SimpleMailMessage mailMessage) {
        this.mailMessage = mailMessage;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

    /**
     * Convenience method for setting a "from" parameter to indicate the previous page.
     * @param from indicator for the originating page
     */
    public void setFrom(String from) {
        this.from = from;
    }

    public void setDelete(String delete) {
        this.delete = delete;
    }

    public void setSave(String save) {
        this.save = save;
    }

	public void setSession(Map session) {
		// TODO Auto-generated method stub
		this.session = session;
	}

	public Long getAdminUserId() {
		SystemAdminUser adminUser = (SystemAdminUser) session.get(WebContextKey.ADMIN_USER);
		return adminUser.getAdminId();
	}
	
	
	
	
	
	// load file
	
	protected File file;
	protected String fileContentType;
	protected String fileFileName;
	protected String name;

    /**
     * Upload the file
     * @return String with result (cancel, input or sucess)
     * @throws Exception if something goes wrong
     */
    public String upload() throws Exception {
         

        // the directory to upload to
        String uploadDir = ServletActionContext.getServletContext().getRealPath("//resources/auto/");

        // write the file to the file specified
        File dirPath = new File(uploadDir);

        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }

        //retrieve the file data
        InputStream stream = new FileInputStream(file);
        
        String extend = fileFileName.substring(fileFileName.lastIndexOf("."));
		int ranNumber = RequestUtil.getRandom(); 
		String destFileName = System.currentTimeMillis() + "_" + ranNumber + extend;
        //write the file to the file specified
        OutputStream bos = new FileOutputStream(uploadDir+"/" + destFileName);
        int bytesRead;
        byte[] buffer = new byte[8192];

        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }

        bos.close();
        stream.close();

        // place the data into the request for retrieval on next page
        getRequest().setAttribute("location", dirPath.getAbsolutePath()
                + Constants.FILE_SEP + fileFileName);
        
        String link =   "/resources/auto" + "/" +destFileName;

        

        return link;
    }

  

    public void setFile(File file) {
        this.file = file;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public File getFile() {
        return file;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public String getFileFileName() {
        return fileFileName;
    }

 
	
	
	
	
	
	
	
	
	
	
	
	
}
